package alertPeopleMsg

import (
	"context"
	"devops-super/api"
	v1 "devops-super/api/alerts/v1"
	"devops-super/internal/dao"
	"devops-super/internal/model/entity"
	"devops-super/internal/model/mymodel"
	"devops-super/internal/service"
	"errors"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"time"
)

type sAlertPeopleMsg struct{}

var cols = dao.AlertPeopleMsgsDemo.Columns()

func init() {
	service.RegisterAlertPeopleMsg(New())
}

func New() *sAlertPeopleMsg {
	return &sAlertPeopleMsg{}
}

// Add 添加告警通知日志
func (*sAlertPeopleMsg) Add(ctx context.Context, in *entity.AlertPeopleMsgsDemo) (err error) {
	// 验证告警日志是否存在
	var alertLogCount int
	alertLogCount, err = dao.AlertLogDemo.Ctx(ctx).Where(dao.AlertLogDemo.Columns().Id, in.AlertLogId).Count()
	if err != nil {
		return err
	}
	if alertLogCount == 0 {
		return errors.New("告警日志不存在")
	}

	// 验证人员是否存在
	var peopleCount int
	peopleCount, err = dao.AlertPeople.Ctx(ctx).Where(dao.AlertPeople.Columns().Id, in.PeopleId).Count()
	if err != nil {
		return err
	}
	if peopleCount == 0 {
		return errors.New("告警人员不存在")
	}

	_, err = dao.AlertPeopleMsgsDemo.Ctx(ctx).Insert(in)
	return
}

// Upt 更新告警通知日志
func (*sAlertPeopleMsg) Upt(ctx context.Context, in *entity.AlertPeopleMsgsDemo) (err error) {
	// 验证通知日志是否存在
	var count int
	count, err = dao.AlertPeopleMsgsDemo.Ctx(ctx).WherePri(in.Id).Count()
	if err != nil {
		return err
	}
	if count == 0 {
		return errors.New("告警通知日志不存在")
	}

	_, err = dao.AlertPeopleMsgsDemo.Ctx(ctx).WherePri(in.Id).OmitNilData().Data(in).Update()
	return
}

// GetPageLst 分页获取告警通知日志列表
func (*sAlertPeopleMsg) GetPageLst(ctx context.Context, req *v1.AlertPeopleMsgGetPageLstReq) (out *api.PageLstRes[*mymodel.AlertPeopleMsgResponse], err error) {
	out = &api.PageLstRes[*mymodel.AlertPeopleMsgResponse]{}
	m := dao.AlertPeopleMsgsDemo.Ctx(ctx).Safe(true)

	// 告警日志ID筛选
	if req.AlertLogId > 0 {
		m = m.Where(cols.AlertLogId, req.AlertLogId)
	}

	// 人员ID筛选
	if req.PeopleId > 0 {
		m = m.Where(cols.PeopleId, req.PeopleId)
	}

	// 通知方式筛选
	if req.NoticeType != "" {
		m = m.Where(cols.NoticeType, req.NoticeType)
	}

	// 状态筛选
	if req.Status != "" {
		m = m.Where(cols.Status, req.Status)
	}

	// 部门ID筛选
	if req.DeptId > 0 {
		m = m.Where(cols.DeptId, req.DeptId)
	}

	// 按时间范围筛选
	if req.TimeRange != nil {
		if len(req.TimeRange) != 2 {
			return nil, gerror.NewCode(gcode.CodeInvalidParameter, "时间范围参数格式错误")
		}
		// 新增时间转换逻辑
		startTime, err := time.Parse(time.RFC3339, req.TimeRange[0])
		if err != nil {
			return nil, gerror.WrapCode(gcode.CodeInvalidParameter, err, "开始时间格式错误")
		}
		endTime, err := time.Parse(time.RFC3339, req.TimeRange[1])
		if err != nil {
			return nil, gerror.WrapCode(gcode.CodeInvalidParameter, err, "结束时间格式错误")
		}
		timeLayout := "2006-01-02 15:04:05"
		timeStr0 := startTime.Local().Format(timeLayout)
		timeStr1 := endTime.Local().Format(timeLayout)
		m = m.WhereBetween(cols.CreatedAt, timeStr0, timeStr1)
	}

	// 分页查询原始实体
	var entities []*entity.AlertPeopleMsgsDemo
	if err = m.OrderDesc(cols.CreatedAt).Offset(req.Offset()).Limit(req.Limit()).ScanAndCount(&entities, &out.Total, false); err != nil {
		return
	}

	// 转换为响应模型
	out.List = make([]*mymodel.AlertPeopleMsgResponse, len(entities))
	for i, e := range entities {
		out.List[i] = &mymodel.AlertPeopleMsgResponse{
			Id:         e.Id,
			AlertLogId: e.AlertLogId,
			PeopleId:   e.PeopleId,
			Msg:        e.Msg,
			NoticeType: e.NoticeType,
			Status:     e.Status,
			StatusMsg:  e.StatusMsg,
			CreatedAt:  e.CreatedAt,
			UpdatedAt:  e.UpdatedAt,
			DeptId:     e.DeptId,
		}
	}
	return
}

// UptStatus 更新告警通知日志状态
func (*sAlertPeopleMsg) UptStatus(ctx context.Context, id int64, status int, statusMsg string) (err error) {
	// 验证通知日志是否存在
	var count int
	count, err = dao.AlertPeopleMsgsDemo.Ctx(ctx).WherePri(id).Count()
	if err != nil {
		return err
	}
	if count == 0 {
		return errors.New("告警通知日志不存在")
	}

	data := map[string]interface{}{
		cols.Status: status,
	}
	if statusMsg != "" {
		data[cols.StatusMsg] = statusMsg
	}

	_, err = dao.AlertPeopleMsgsDemo.Ctx(ctx).WherePri(id).Data(data).Update()
	return
}

// Del 删除告警通知日志
func (*sAlertPeopleMsg) Del(ctx context.Context, id int64) (err error) {
	// 验证通知日志是否存在
	var count int
	count, err = dao.AlertPeopleMsgsDemo.Ctx(ctx).WherePri(id).Count()
	if err != nil {
		return err
	}
	if count == 0 {
		return errors.New("告警通知日志不存在")
	}

	_, err = dao.AlertPeopleMsgsDemo.Ctx(ctx).WherePri(id).Delete()
	return
}

// GetOne 获取一条告警通知日志
func (*sAlertPeopleMsg) GetOne(ctx context.Context, id int64) (out *mymodel.AlertPeopleMsgResponse, err error) {
	var ent *entity.AlertPeopleMsgsDemo
	err = dao.AlertPeopleMsgsDemo.Ctx(ctx).WherePri(id).Scan(&ent)
	if err != nil {
		return
	}

	out = &mymodel.AlertPeopleMsgResponse{
		Id:         ent.Id,
		AlertLogId: ent.AlertLogId,
		PeopleId:   ent.PeopleId,
		Msg:        ent.Msg,
		NoticeType: ent.NoticeType,
		Status:     ent.Status,
		StatusMsg:  ent.StatusMsg,
		CreatedAt:  ent.CreatedAt,
		UpdatedAt:  ent.UpdatedAt,
		DeptId:     ent.DeptId,
	}
	return
}

// GetOptions 获取表单选项
func (*sAlertPeopleMsg) GetOptions(ctx context.Context, in *v1.AlertPeopleMsgGetOptionsReq) (out *v1.AlertPeopleMsgGetOptionsRes, err error) {
	out = new(v1.AlertPeopleMsgGetOptionsRes)

	// 根据字段类型返回不同的选项
	if in.FieldKey == "status" {
		// 返回通知状态选项
		out.Options = []*api.FormOptionsItem{
			{Value: 0, Label: "通知中"},
			{Value: 1, Label: "成功"},
			{Value: -1, Label: "失败"},
		}
	} else if in.FieldKey == "noticeType" {
		// 返回通知方式选项
		out.Options = []*api.FormOptionsItem{
			{Value: "sms", Label: "短信"},
			{Value: "email", Label: "邮件"},
		}
	} else {
		// 默认返回空选项
		out.Options = []*api.FormOptionsItem{}
	}

	return
}

// BatchDel 批量删除告警通知日志
func (*sAlertPeopleMsg) BatchDel(ctx context.Context, ids []int64) (err error) {
	if len(ids) == 0 {
		return errors.New("请选择要删除的通知日志")
	}

	// 验证所有通知日志是否存在
	var existCount int
	existCount, err = dao.AlertPeopleMsgsDemo.Ctx(ctx).WhereIn(cols.Id, ids).Count()
	if err != nil {
		return err
	}

	if existCount != int(len(ids)) {
		return errors.New("部分告警通知日志不存在")
	}

	// 批量删除
	_, err = dao.AlertPeopleMsgsDemo.Ctx(ctx).WhereIn(cols.Id, ids).Delete()
	return
}
